<template>
  <a-row justify="space-around">
    <a-col :span="17" style="background-color: #fff; padding: 15px 40px !important; border-radius: 10px;">
      <div class="conditions">
        <div class="condition-item">
          <div class="condition-label">省份：</div>
          <div class="condition-content">
            <a-radio-group v-model:value="formData.province" @change="handleProvinceChange">
              <a-space size="small" wrap>
                <a-radio-button 
                  :class="formData.province === '' ? 'fee-active' : ''"
                  style="border: none; font-weight: normal;"
                  value=""
                >
                  全部
                </a-radio-button>
                <a-radio-button v-for="item in optionsProvince" 
                  :key="item.value"
                  :class="formData.province === item.value ? 'fee-active' : ''"
                  style="border: none; font-weight: normal;"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-radio-button>
              </a-space>
            </a-radio-group>
          </div>
        </div>
        <div class="condition-item">
          <div class="condition-label">城市：</div>
          <div class="condition-content">
            <a-radio-group v-model:value="formData.city" @change="handleCityChange">
              <a-space size="small" wrap>
                <a-radio-button 
                  :class="formData.city === '' ? 'fee-active' : ''"
                  style="border: none; font-weight: normal;"
                  value=""
                >
                  全部
                </a-radio-button>
                <a-radio-button v-for="item in optionsCity"
                  :key="item.value"
                  :class="formData.city === item.value ? 'fee-active' : ''"
                  style="border: none; font-weight: normal;"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-radio-button>
              </a-space>
            </a-radio-group>
          </div>
        </div>
        <div class="condition-item">
          <div class="condition-label">收费类型：</div>
          <div class="condition-content">
            <a-radio-group v-model:value="formData.feeType" @change="handleFeeTypeChange">
              <a-space size="small">
                <a-radio-button :class="formData.feeType === 'N' ? 'fee-active' : ''"
                  style="border: none; font-weight: normal;" value="N">免费
                </a-radio-button>
                <a-radio-button :class="formData.feeType === 'Y' ? 'fee-active' : ''"
                  style="border: none; font-weight: normal;" value="Y">收费
                </a-radio-button>
              </a-space>
            </a-radio-group>
          </div>
        </div>
        <div class="condition-item" v-show="formData.feeType === 'Y'">
          <div class="condition-label">租金：</div>
          <div class="condition-content">
            <a-space :size="10">
              <a-input-number placeholder="最小金额" id="startAmount" v-model:value="formData.startAmount" />
              <span class="font-bold">—</span>
              <a-input-number placeholder="最大金额" id="endAmount" v-model:value="formData.endAmount" />
            </a-space>
          </div>
        </div>
      </div>
      <a-row align="middle" justify="space-between">
        <div class="order-query">
          <a-tabs v-model:activeKey="order" @change="changeFishSiteOrder">
            <a-tab-pane key="" tab="全部" />
            <a-tab-pane key="create_time" tab="最新" force-render />
            <a-tab-pane key="avg_rating" tab="评分最高" />
          </a-tabs>
        </div>
        <div class="search-query">
          <a-input-search class="fish-site-name-input" enter-button v-model:value="formData.name" placeholder="搜索"
            @search="searchName" />
        </div>
      </a-row>
      <div class="angling-container" v-loading="loading">
        <a-row :gutter="24">
          <a-col :span="8" class="fish-site-box" v-for="(fishSite, index) in fishSiteList" :key="fishSite.fishSiteId"
            @click="toDetail(fishSite)">
            <a-card hoverable style="width: 100%; border-radius: 20px;">
              <template #cover>
                <img style="width: 100%; height: 202px;" alt="example"
                  :src="getImageUrls(fishSite.imageUrl)[0]" />
              </template>
              <a-card-meta :title="fishSite.name">
                <template #description>
                  <a-row justify="space-between" :gutter="24">
                    <a-col :span="17">
                      <span class="fish-site-address"> {{ fishSite.province }}
                        {{ fishSite.city }}
                      </span>
                    </a-col>
                    <a-col :span="7" v-if="fishSite.avgRating" class="fish-site-avg-rating">
                      <span>{{ fishSite.avgRating }}</span>
                      <StarFilled :style="{ color: '#F7BA2A', paddingTop: '1px' }" />
                    </a-col>
                  </a-row>
                </template>
              </a-card-meta>
            </a-card>
          </a-col>
        </a-row>
        <a-row class="page-box" justify="center">
          <a-pagination v-model:current="pageQuery.pageNum" v-model:pageSize="pageQuery.pageSize" hideOnSinglePage
            :showSizeChanger="false" :total="total" show-less-items :show-total="total => `总数 ${total} `"
            @change="updatePageNum" />
        </a-row>
      </div>
      <a-empty v-show="fishSiteList.length <= 0">
        <template #description>
          <span>
            暂无内容
          </span>
        </template>
      </a-empty>
    </a-col>
    <a-col :span="6" style="padding-left: 10px;">
      <a-card title="评论最多" class="hot-comments-card">
        <template v-for="(item, index) in hotFishSiteList" :key="item.fishSiteId">
          <div class="hot-fish-site-item" @click="toDetail(item)">
            <div class="hot-fish-site-index">{{ index + 1 }}</div>
            <div class="hot-fish-site-content">
              <div class="hot-fish-site-name">{{ item.name }}</div>
              <div class="hot-fish-site-info">
                <span>{{ item.province }} {{ item.city }}</span>
                <span v-if="item.avgRating" class="rating">
                  {{ item.avgRating }}
                  <StarFilled :style="{ color: '#F7BA2A', fontSize: '12px' }" />
                </span>
              </div>
            </div>
          </div>
          <a-divider v-if="index !== hotFishSiteList.length - 1" style="margin: 12px 0" />
        </template>
      </a-card>
    </a-col>
  </a-row>

  <!-- 使用登录提示模态框组件 -->
  <login-tooltip-mode ref="loginModal" />
</template>

<script setup lang="ts">
import '@/styles/angling.scss';
import { AnglingQuery, AnglingVO } from "@/api/front/angling/types";
import { useRouter } from 'vue-router';
import type { SelectProps } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { anglingList, searchOptions } from "@/api/front/angling";
import { StarFilled, InfoCircleOutlined } from '@ant-design/icons-vue';
import { useUserStore } from '@/store/modules/user';
import LoginTooltipMode from '@/components/LoginTooltipMode/index.vue';
let loading = ref(false)
let order = ref("")
let total = ref(500)
const formDataRef = ref<FormInstance>();


const pageQuery = reactive({
  pageSize: 10,
  pageNum: 1,
  orderByColumn: '',
  isAsc: 'desc'
})

const formData = reactive<AnglingQuery>({
  feeType: '',
  province: '',
  city: ''
})

let fishSiteList = reactive<Array<AnglingVO>>([])
let hotFishSiteList = ref<Array<AnglingVO>>([])


/**
 * 监听pageNum变化
 */
const updatePageNum = (value: number) => {
  getFishSiteList()
}

/**
 * 切换钓点排序
 * @param activeKey
 */
const changeFishSiteOrder = (activeKey: string) => {
  // 1 赋值排序
  if (activeKey === '') {
    pageQuery.orderByColumn = null
    pageQuery.isAsc = null
  } else {
    pageQuery.orderByColumn = activeKey
    pageQuery.isAsc = 'desc'
  }
  getFishSiteList()
}

/**
 * 初始化页面
 */
const getFishSiteList = async () => {
  loading.value = true
  const res = await anglingList(pageQuery, formData)
  fishSiteList.splice(0, fishSiteList.length, ...res.data.rows);
  total.value = res.data.total
  loading.value = false
}

const optionsProvince = ref<SelectProps['options']>([]);
const handleDropdownProvince = async (open) => {
  if (!open || optionsProvince.value.length > 0) return; // 如果下拉菜单关闭或已有数据，则不执行
  const { data } = await searchOptions('province');

  // 确保data是一个数组，且有内容
  if (Array.isArray(data) && data.length) {
    // 转成 options格式
    const provinceOptions = data.map((item) => ({
      label: item,
      value: item
    }));

    optionsProvince.value = provinceOptions;
  }
}
const handleProvinceChange = (value: string) => {
  getFishSiteList()
};

let cityOptionLoading = ref(false)
const optionsCity = ref<SelectProps['options']>([]);
const handleDropdownCity = async (open) => {

  if (optionsCity.value.length > 0) return; // 如果下拉菜单关闭或已有数据，则不执行

  cityOptionLoading.value = true
  const { data } = await searchOptions('city');
  // 确保data是一个数组，且有内容
  if (Array.isArray(data) && data.length) {
    // 转成 options格式
    const cityOptions = data.map((item) => ({
      label: item,
      value: item
    }));

    optionsCity.value = cityOptions;
  }

  cityOptionLoading.value = false
}
const handleCityChange = () => {
  getFishSiteList()
};

const handleFeeTypeChange = () => {
  getFishSiteList()
}

/**
 * 过滤省份
 * @param input 输入框值
 * @param option 选项列表
 */
const filterOption = (input: string, option: any) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const searchName = (value: string) => {
  getFishSiteList()
}
const router = useRouter()
const toDetail = (fishSite: AnglingVO) => {
  // 检查用户是否登录
  if (!userStore.userId) {
    loginModal.value?.show();
    return;
  }
  
  // 已登录则正常跳转
  const routeUrl = router.resolve({
    name: '钓场详情',
    params: {
      fishSiteId: fishSite.fishSiteId
    }
  });
  window.open(routeUrl.href, '_blank');
}

const getHotFishSiteList = async () => {
  const query = {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'rating_count',
    isAsc: 'desc'
  }
  const res = await anglingList(query, {})
  hotFishSiteList.value = res.data.rows
}

const loginModal = ref();
const userStore = useUserStore();

const getImageUrls = (imageUrl: string) => {
    if (!imageUrl) return [];
    // 如果包含逗号，按逗号分隔
    if (imageUrl.includes(',')) {
        return imageUrl.split(',');
    }
    // 如果是单张图片，直接返回包含该图片的数组
    return [imageUrl];
}

onMounted(() => {
  getFishSiteList()
  getHotFishSiteList()
  handleDropdownProvince(true)
  handleDropdownCity(true)
})

</script>

<style scoped lang="scss">
.conditions {
  border-bottom: 1px solid #F0F0F0;
  padding: 15px 0;

  .condition-item {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;

    .condition-label {
      width: 9.33%;
      margin-right: 15px;
      font-weight: bolder;
      color: #555;
      line-height: 32px;
      text-align: right;
    }

    .condition-content {
      flex: 1;
    }
  }

  .ant-radio-button-wrapper {
    padding-inline: 10px;
    margin-bottom: 8px;

    &:hover {
      color: #1890ff;
      background: #e6f7ff;
    }
  }

  .fee-active {
    color: #1890ff !important;
    background: #e6f7ff !important;
  }
}

.angling-container {
  margin-top: 20px;

  .fish-site-box {
    margin-top: 20px;

    .fish-site-name {
      padding-right: 3px;
      color: #1d1e1f;
    }

    .fish-site-avg-rating {
      display: flex;
      align-items: center;

      span {
        margin-right: 5px;
      }
    }
  }

  .page-box {
    margin-top: 25px;
  }
}

.hot-fish-site-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  cursor: pointer;

  &:hover {
    .hot-fish-site-name {
      color: #1890ff;
    }
  }

  .hot-fish-site-index {
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    background-color: #f0f0f0;
    border-radius: 4px;
    margin-right: 12px;
    font-weight: bold;
  }

  .hot-fish-site-content {
    flex: 1;

    .hot-fish-site-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .hot-fish-site-info {
      font-size: 12px;
      color: #999;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .rating {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }
}

.hot-comments-card {
  width: 100%;
  border-radius: 20px;
  background: #fff;

  :deep(.ant-card-head) {
    background: linear-gradient(180deg, #e6f7ff 0%, #ffffff 100%);
    border-bottom-color: rgba(0, 0, 0, 0.1);
    .ant-card-head-title {
      color: #1890ff;
      font-weight: bold;
    }
  }
}
</style>